#include "main.h"


void delay(uint16_t t)
{
  while(t--);
}

void system_init(void)
{
  CLK_DeInit();
  CLK_HSICmd(ENABLE);
  CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1);
}

void timer_init(void)
{
  TIM4_TimeBaseInit(TIM4_PRESCALER_128, 124);   // 1ms
  TIM4_ClearFlag(TIM4_FLAG_UPDATE);
  TIM4_ITConfig(TIM4_IT_UPDATE, ENABLE);
  TIM4_Cmd(ENABLE);
}

void iic_init(void)
{
  GPIO_Init(GPIOB, GPIO_PIN_4, GPIO_MODE_OUT_OD_HIZ_FAST);
  GPIO_Init(GPIOB, GPIO_PIN_5, GPIO_MODE_IN_FL_NO_IT);
  for(uint8_t i=0;i<32&&!GPIO_ReadInputPin(GPIOB, GPIO_PIN_5);i++)
  {
    GPIO_WriteReverse(GPIOB, GPIO_PIN_4);
    delay(0x20);
  }
  I2C_DeInit();
  I2C_Init(100000, 0x00, I2C_DUTYCYCLE_2, I2C_ACK_CURR, I2C_ADDMODE_7BIT, 16);
  I2C_Cmd(ENABLE);
}

int main(void)
{
  system_init();
  iic_init();
  output_init();
  modbus_init();
  switch_init();
  clock_init();
  oled_init();
  rc38_init();
  timer_init();
  enableInterrupts();
  
  switch_auto();
  output_set(1);
  while(1)
  {
    modbus_fun();
    oled_fun();
    rc38_fun();
  }
}
/*
struct
{
  u8 file[64];
  u32 len;
}main_err;*/

void assert_failed(u8* file, u32 line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
 /* main_err.len = line;
  for(uint8_t i=0;i<64;i++)
  {
    main_err.file[i] = *file++;
    if(*file=='\0')
    {
      break;
    }
  }*/
  
  /* Infinite loop */
  while (1)
  {
  }
}